﻿# 运行所有错误测试文件
# 这些测试预期会失败，用于验证错误处理机制

# Get the script directory
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent $ScriptDir
$ErrorTestDir = Join-Path $ScriptDir "tests\errors"

Write-Host "开始运行错误测试..." -ForegroundColor Green
Write-Host "注意：这些测试预期会失败，用于验证错误处理机制`n" -ForegroundColor Yellow

Set-Location $ProjectRoot

# 错误测试文件列表
$errorTests = @(
    @{ Name = "无效指令测试"; File = "test_invalid_instruction.asm"; ExpectedError = "暂不支持编码指令" },
    @{ Name = "无效寄存器测试"; File = "test_invalid_register.asm"; ExpectedError = "无效的16位寄存器" },
    @{ Name = "操作数数量错误测试"; File = "test_operand_count.asm"; ExpectedError = "需要" },
    @{ Name = "立即数超出范围测试"; File = "test_immediate_range.asm"; ExpectedError = "超出" },
    @{ Name = "移位次数超出范围测试"; File = "test_shift_range.asm"; ExpectedError = "移位次数" },
    @{ Name = "语法错误测试"; File = "test_syntax_error.asm"; ExpectedError = "语法错误" },
    @{ Name = "未定义标签测试"; File = "test_undefined_label.asm"; ExpectedError = "未定义" }
)

$passedTests = 0
$failedTests = 0
$totalTests = $errorTests.Count

foreach ($test in $errorTests) {
    $testFile = Join-Path $ErrorTestDir $test.File
    Write-Host "测试: $($test.Name) ($($test.File))..." -ForegroundColor Cyan -NoNewline
    
    # 运行测试并捕获输出（只捕获stderr，因为错误消息在stderr中）
    $process = Start-Process -FilePath "cargo" -ArgumentList "run", "--", $testFile, "nul" -NoNewWindow -Wait -PassThru -RedirectStandardError "error_output.txt" -RedirectStandardOutput "stdout.txt"
    $exitCode = $process.ExitCode
    
    # 读取错误输出
    $errorOutput = ""
    if (Test-Path "error_output.txt") {
        $errorOutput = Get-Content "error_output.txt" -Raw -Encoding UTF8
        Remove-Item "error_output.txt" -ErrorAction SilentlyContinue
    }
    if (Test-Path "stdout.txt") {
        Remove-Item "stdout.txt" -ErrorAction SilentlyContinue
    }
    
    if ($exitCode -ne 0) {
        # 检查错误消息是否包含预期的错误关键词
        if ($errorOutput -match $test.ExpectedError) {
            Write-Host " ✓ 通过" -ForegroundColor Green
            $passedTests++
        } else {
            Write-Host " ✗ 失败（错误消息不匹配）" -ForegroundColor Red
            Write-Host "   预期包含: $($test.ExpectedError)" -ForegroundColor Yellow
            $errorPreview = if ($errorOutput.Length -gt 200) { $errorOutput.Substring(0, 200) + "..." } else { $errorOutput }
            Write-Host "   实际输出: $errorPreview" -ForegroundColor Yellow
            $failedTests++
        }
    } else {
        Write-Host " ✗ 失败（应该产生错误但没有）" -ForegroundColor Red
        $failedTests++
    }
}

Write-Host "`n错误测试完成！" -ForegroundColor Green
Write-Host "通过: $passedTests / $totalTests" -ForegroundColor $(if ($passedTests -eq $totalTests) { "Green" } else { "Yellow" })
Write-Host "失败: $failedTests / $totalTests" -ForegroundColor $(if ($failedTests -eq 0) { "Green" } else { "Red" })

if ($failedTests -gt 0) {
    exit 1
}

